package com.zhongxiangspace.filter;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

public class MyOncePerRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
      String requestedWith=((HttpServletRequest)servletRequest).getHeader("X-Requested-With");
        System.out.println();
       if (StringUtils.isNotEmpty(requestedWith)&&StringUtils.equals(requestedWith,"XMLHttpRequest")&&!((HttpServletRequest)servletRequest).getRequestURL().toString().contains("Loin")){
           servletResponse.setCharacterEncoding("UTF-8");//设置编码
           servletResponse.setContentType("application/json");//服务器响应类型
           PrintWriter out = servletResponse.getWriter();
           out.write( "alert('成功了');");
           out.close();
           out.flush();
       }else{
           filterChain.doFilter(servletRequest, servletResponse);
       }
    }
}
